<template>
  <div>
    <div class="app_card mb-2 pt-4 pb-4">
      <div class="d-flex justify-content-between search-form">
        <div class="flex-grow-1">
          <el-select clearable v-model="queryForm.buildingId" placeholder="请选择大楼" class="w200px mr-3" autocomplete="off"
            @change="floorFetch">
            <el-option v-for="item in buildingStore.bildingList" :key="item.id" :label="item.name"
              :value="item.id"></el-option>
          </el-select>
          <el-select clearable v-model="queryForm.floorId" placeholder="请选择楼层" class="w200px mr-3" autocomplete="off"
            @change="roomFetch">
            <el-option v-for="item in floorStore.floorList" :key="item.id" :label="item.name"
              :value="item.id"></el-option>
          </el-select>
          <el-select clearable v-model="queryForm.roomId" placeholder="请选择教室" class="w200px mr-3" autocomplete="off">
            <el-option v-for="item in roomStore.roomList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <el-button type="primary" plain @click="onRefresh()">查询</el-button>
          <el-button type="info" @click="onReset()" link>重置</el-button>
        </div>
        <div class="d-flex">
          <el-button type="primary" @click="onAdd()">新增</el-button>
        </div>
      </div>
    </div>
    <div class="app_card pt-4  pb-5">
      <el-table v-loading="loading" element-loading-text="查询中..." stripe size="large" :data="dataOfTable"
        height="calc(100vh - 300px)" sortable="custom" @sort-change="handleSortChange"
        @selection-change="handleSelectionChange">

        <el-table-column width="200" label="门锁ID" prop="lockId" align="center" show-overflow-tooltip>
          <template #default="scope">{{ scope.row.lockId }}</template>
        </el-table-column>
        <el-table-column label="大楼" prop="building" align="center" show-overflow-tooltip>
          <template #default="scope">{{ scope.row.building }}</template>
        </el-table-column>
        <el-table-column label="楼层" prop="floor" align="center" show-overflow-tooltip>
          <template #default="scope">{{ scope.row.floor }}</template>
        </el-table-column>
        <el-table-column label="教室" prop="room" align="center">
          <template #default="scope">{{ scope.row.room }}</template>
        </el-table-column>
        <el-table-column label="门锁名称" prop="lockName" align="center" show-overflow-tooltip>
          <template #default="scope">{{ scope.row.lockName }}</template>
        </el-table-column>
        <el-table-column fixed="right" label="门锁控制" width="260" align="center">
          <template #default="scope">
            <el-button @click="openLock(scope.row, 1)" link type="primary">常开</el-button>
            <el-button @click="openLock(scope.row, 2)" link type="primary">常关</el-button>
            <el-button @click="openLock(scope.row, 3)" link type="primary">开锁</el-button>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="onEditRow(scope.row)">编辑
            </el-button>
            <el-button link type="primary" @click="onDeleteRow(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>

      </el-table>
      <Pagination ref="paginationRef" @handleChange="handleChange" />

    </div>
    <EditDialog ref="editDialogRef" @success="loadData()"></EditDialog>
  </div>
</template>
  
<script setup>
/**
 */
import { ref, nextTick } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';
//组件
import Pagination from '@/components/pagination/index.vue';
import EditDialog from './EditDialog.vue';
import { roomTypeList } from '@/apis/model/RoomModel';
import { findValue } from '@/utils/EsCommon';
import { ElLoading } from 'element-plus'
import useBuildingStore from '@/stores/useBuildingStore';
import useFloorStore from '@/stores/useFloorStore';
import useRoomStore from '@/stores/useRoomStore';

// ======================================================
//                      变量声明
// ======================================================
const buildingStore = useBuildingStore();
const floorStore = useFloorStore();
const roomStore = useRoomStore();

// ======================================================
//                      变量声明
// ======================================================
const loading = ref(false);
// 组件引用
const paginationRef = ref(null);
const editDialogRef = ref(null);
// 表格数据
const roomTypeOption = ref(roomTypeList);
const dataOfTable = ref([]);
// 选项数据


// 表格查询参数
const queryForm = ref({
  buildingId: "",
  floorId: "",
  roomId: "",
})
// 表格查询参数
const queryParam = ref({
  sort: "Id",
  order: "asc",
  limit: 10,
  page: 1,
  query: ""
})
// 表格多选数据
const multipleSelection = ref([]);

// ======================================================
//                      点击操作
// ======================================================
// 点击快速搜索按钮
const onReset = () => {
  queryForm.value.buildingId = ""
  queryForm.value.floorId = ""
  queryForm.value.roomId = ""
  onRefresh()
}
// 点击刷新按钮
const onRefresh = () => {
  queryParam.value.page = 1;
  paginationRef.value?.changeTotal({ totalCount: 0 })
  loadData();
}

// 点击新增按钮
const onAdd = () => {
  editDialogRef.value.show(null, '添加');
}


const openLock = (row, type) => {
  var data = {
    lockId: row.lockId,
    unitNo: row.unitNo,
    lock: type == 2 ? 2 : 1,
  };
  let url = type == 3 ? ApiUrls.lockUnlock : ApiUrls.lockConfig;
  const loadingInstance = ElLoading.service({ text: '加载中...' })

  EsAjax.post(url, data).then(res => {
    if (res.data.code != 200) {
      ElMessage.warning(res.data.data + res.data.msg);
      return;
    }

    ElMessage.success('开锁成功！');
  }).catch(err => {
    ElMessage.error('开锁失败！');
  }).finally(() => {
    nextTick(() => {
      // Loading should be closed asynchronously
      loadingInstance.close()
    })
  })


}




// 点击行内删除按钮
const onDeleteRow = (row) => {
  ElMessageBox.confirm("确定要删除该记录吗？", "警告").then(() => {
    EsAjax.post(ApiUrls.smartlockDelete, { ids: String(row.id) })
      .then(res => {
        if (res.data.code != 200) {
          ElMessage.warning(res.data.msg + res.data.data);
          return;
        }
        ElMessage.success('操作成功');
        loadData();
      })
      .catch(err => { ElMessage.error("网络错误：", err.message) });
  }).catch(() => {

  });
  console.log(row)
}


// 点击行内编辑按钮
const onEditRow = (row) => {
  editDialogRef.value.show(row.lockId, '编辑 ', row);
}

// ======================================================
//                      处理事件
// ======================================================

// 处理表格全选
const handleSelectionChange = (val) => {
  console.log(val)
  multipleSelection.value = val
}

// 处理表格排序
const handleSortChange = (column) => {
  queryParam.value.orderby = column.prop + ' ' + (column.order == 'descending' ? 'desc' : 'asc');
  console.log(queryParam.value);
  loadData();
}
// 处理分页尺寸
const handleChange = (data = null) => {
  queryParam.value.page = data?.page;
  queryParam.value.limit = data?.limit;
  loadData();
}

// ======================================================
//                      处理事件
// ======================================================
const loadData = () => {
  let _queryParam = queryParam.value
  _queryParam.query = ''
  if (queryForm.value.buildingId) {
    _queryParam.query += ",buildingId=" + queryForm.value.buildingId;
  }
  if (queryForm.value.roomId) {
    _queryParam.query += ",roomId=" + queryForm.value.roomId;
  }
  if (queryForm.value.floorId) {
    _queryParam.query += ",floorId=" + queryForm.value.floorId;
  }
  _queryParam.offset = (_queryParam.page - 1) * _queryParam.limit || 0;
  loading.value = true

  EsAjax.post(ApiUrls.smartlockDatagrid, { ..._queryParam }).then(res => {
    if (res.data.code != 200) {
      ElMessage.warning(res.data.data + res.data.msg);
      return;
    }
    let { list, totalCount } = res.data.data
    dataOfTable.value = list;
    paginationRef.value?.changeTotal({ totalCount: totalCount })
  }).catch(err => {
    ElMessage.error(err.message);
  }).finally(() => {
    loading.value = false
  })
}

// 加载楼层数据
const floorFetch = (e) => {
  floorStore.getFloorList(e)
  queryForm.value.floorId = ""
  queryForm.value.roomId = ""
}
// 加载教室数据
const roomFetch = (e) => {
  roomStore.getRoomList(e)
  queryForm.value.roomId = ""
}
//加载大楼数据
buildingStore.getBuildList()
loadData();
</script>
  
